<template>
  <div class="sign">
    <div class="header_body">
      <header-nav :leftArrow="true" titelText="签名设置"></header-nav>
    </div>

    <div class="signature">
      <van-image v-if="sign != ''" :src="sign" :confirm-button-text="'保存'"
        style="height: calc(100% - 130px);padding:10px;" />
      <div style="text-align: center; padding: 0 16px">
        <van-button v-if="sign != ''" block type="primary" @click="reSign()" style="height: 47px" plain>
          重新签名
        </van-button>
      </div>
      <van-signature v-if="sign == ''" background-color="#f7f7f7" @submit="onSubmit" @clear="onClear" />
    </div>
  </div>
</template>
<script setup>
import { showSuccessToast, showFailToast } from 'vant'
import { imgUrlToBase64 } from '../../util/util'
const router = useRouter()
const { useLogin, usePublic } = $globalStore
const route = useRoute()
const sign = ref('')
const signs = ref(route.query.sign)

const onSubmit = async (data) => {
  sign.value = data.image
  const res = await usePublic.uploadFile2({ contents: data.image })
  if (res.code == 0) {
    let params = {
      userSign: res.data.fileIds[0],
    }
    const r = await useLogin.setUserSign(params)
    if (r.code == 0) {
      let userInfo = JSON.parse(sessionStorage.getItem('userInfo'))
      console.log(userInfo, 'userInfo');
      let data = { ...userInfo, userSign: res.data.fileIds[0] }
      console.log(data);
      sessionStorage.setItem('userInfo', JSON.stringify(data))
      showSuccessToast('设置成功')
      router.go(-1)
    } else {
      showFailToast(res.message)
    }
  }
}

const reSign = () => {
  sign.value = ''
}

const onClear = () => { }
onMounted(async () => {
  if (signs.value != '') {
    const r = await usePublic.bindFileUrl(signs.value)
    if (r.code == 0) {
      imgUrlToBase64(r.data).then((s) => {
        sign.value = s
      })
    }
  } else {
    sign.value = ''
  }
})
</script>
<style lang="scss" scoped>
.sign {
  width: 100%;
  height: calc(100%);
  overflow-y: hidden;
  background-color: #ffffff;

  .signature {
    // width: 100%;
    height: 100%;
    margin-top: 46px;
    text-align: center;
  }
}

.sign .van-signature {
  height: calc(100% - 110px) !important;
}

::v-deep .van-signature__content {
  height: 100% !important;
}
</style>
